var appid = 'wx8cec766c8474008e';
var secret = '78af118201c9a749292b5acb084756e1';
var Promise = require("bluebird");
var https = require('https');
var sign = require('./sign.js');
module.exports.getAccessToken = getAccessToken = function(){
  var url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appid+'&secret='+secret;
  return new Promise(function(resolve, reject){
    https.get(url, (res) => {
      console.log('get response Code :' + res.statusCode);
      res.on('data', (d)=>{
        var access_token = JSON.parse(d).access_token;
        console.log("1-access_token=>" + access_token);
        resolve(access_token);
      });
    })
    .on('error', (e) => {
      reject(e);
      console.log(`Got error: ${e.message}`);
    });
  });
}
module.exports.getTicket = getTicket = function(){
  return new Promise(function(resolve,reject){
    var access_token_Promise = getAccessToken();
    access_token_Promise.then(function(access_token){
      console.log("2-access_token=>" + access_token);
      var url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi';
      https.get(url, (res) => {
        console.log('get response Code :' + res.statusCode);
        res.on('data', (d)=>{
          var ticket = JSON.parse(d).ticket;
          console.log("1-ticket=>" + ticket);
          resolve(ticket);
        });
      })
      .on('error', (e) => {
        reject(e);
        console.log(`Got error: ${e.message}`);
      });
    });
  });
}
module.exports.getSignature = function(){
  return new Promise(function(resolve,reject){
    var ticket_promise = getTicket();
    ticket_promise.then(function(ticket){
      console.log("2-ticket=>" + ticket);
      var ret = sign(ticket, 'http://tzpw1.ngrok.natapp.cn/scanQRCode/');//todo: url地址应为动态生成  网页可由：location.href.split('#')[0] 获取
      resolve(ret);
    });
    ticket_promise.error(function(e){
      reject(e);
    });
  });

}
